import os
import platform
import sys

from PySide6.QtCore import Qt, QRectF
from PySide6.QtGui import QPainter, QColor, QIcon, QPixmap
from PySide6.QtSvg import QSvgRenderer
from PySide6.QtWidgets import QSystemTrayIcon

from utils.capi import is_theme_light
from utils.log import logger

script_path = os.path.abspath(os.path.dirname(sys.argv[0]))


class MainSystemTray(QSystemTrayIcon):
    def __init__(self, main):
        super().__init__()
        self.main = main

        self.color = QColor('#000000') if platform.system() == 'Windows' and is_theme_light() else QColor('#ffffff')
        self.parse_svg()

        pixmap = QPixmap(16, 16)
        pixmap.fill(Qt.GlobalColor.transparent)

        painter = QPainter(pixmap)
        painter.setBrush(self.color)

        svg_path = os.path.join(script_path, 'src/icon.svg')
        svg_renderer = QSvgRenderer(svg_path)
        svg_renderer.setAspectRatioMode(Qt.AspectRatioMode.KeepAspectRatio)

        svg_renderer.render(painter, QRectF(0, 0, 16, 16))
        painter.end()

        self.setIcon(QIcon(pixmap))

        self.setContextMenu(self.main.menu)
        self.setVisible(True)

    def parse_svg(self):
        import xml.etree.ElementTree as ET

        logger.debug('script_path: {}'.format(script_path))
        svg_path = os.path.join(script_path, 'src/icon.svg')
        tree = ET.parse(svg_path)
        root = tree.getroot()

        for path in root.findall('.//{http://www.w3.org/2000/svg}path'):
            path.set('fill', self.color.name())

        tree.write(svg_path)
